package org.platform.tool.util;

import com.thoughtworks.xstream.XStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 用于生产xml以及反解析的工具类
 *
 * @author FengJie
 * @date 2018/5/10
 */
@Slf4j
public class XmlUtils {
    public static final String XML_PREFIX = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";

    /**
     * Bean转XML
     *
     * @param bean
     * @return
     */
    public static String beanToXml(Object bean) {
        try {
            XStream xStream = new XStream();
            //使用注解
            xStream.autodetectAnnotations(true);
            //忽略属性 class
            xStream.aliasSystemAttribute(null, "class");
            return StringUtils.join(XML_PREFIX, xStream.toXML(bean));
        } catch (Exception e) {
            log.error("XStream实体类转xml文件异常,错误信息: ", e);
        }
        return null;
    }

    /**
     * 自定义转换格式
     *
     * @param xStream 自定义的xStream
     * @param bean
     * @return
     */
    public static String beanToXml(XStream xStream, Object bean) {
        try {
            return StringUtils.join(XML_PREFIX, xStream.toXML(bean));
        } catch (Exception e) {
            log.error("XStream实体类转xml文件异常,错误信息: ", e);
        }
        return null;
    }

    /**
     * xmlToBean
     *
     * @param xml            xml文档
     * @param clazz          返回的实体类
     * @param useAnnotations 使用注解
     * @param interFaceFile  文件一级主题
     *                       相当于第一级<></>
     * @param <T>
     * @return Bean
     */
    public static <T> T xmlToBean(String xml, Class<T> clazz, boolean useAnnotations, String interFaceFile) {
        XStream xStream = new XStream();
        xStream.alias(interFaceFile, clazz);
        xStream.autodetectAnnotations(useAnnotations);
        return xmlToBean(xStream, xml, clazz);
    }

    /**
     * xml转实体类
     *
     * @param xml
     * @return
     */
    public static <T> T xmlToBean(String xml, Class<T> clazz, boolean useAnnotations) {
        XStream xStream = new XStream();
        //使用注解
        xStream.autodetectAnnotations(useAnnotations);
        return xmlToBean(xStream, xml, clazz);

    }

    /**
     * 自定义 xml转实体类
     *
     * @param xStream 自定义xStream
     * @return
     */
    private static <T> T xmlToBean(XStream xStream, String xml, Class<T> clazz) {
        return (T) xStream.fromXML(xml);
    }

}
